package com.tfjybj.itoo.exam.provider.controller;

import com.dmsdbj.itoo.tool.business.ItooResult;
import com.tfjybj.itoo.exam.entity.ExamineeEntity;
import com.tfjybj.itoo.exam.entity.PaperRecordEntity;
import com.tfjybj.itoo.exam.model.*;
import com.tfjybj.itoo.exam.provider.service.ExamineeService;
import com.tfjybj.itoo.exam.provider.service.OnlineExamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * OnlineExamController
 *
 * @author 任蒙蒙
 * @version 2.0.0
 * @since 2.0.0 2018-11-16 08:55:53
 */
@Api(tags = {"onlineExam接口"})
@RequestMapping(value = "onlineExam")
@RestController
@Slf4j
public class OnlineExamController {


    /**
     * 1.
     * 2.根据考试id查询考生须知 {@link OnlineExamController#queryExamNotes}
     * 3.在线考试：根据学生ID生成本次考试试卷{@link OnlineExamController#findPaperByStudentIdForOnlineExam}
     *
     */

    @Resource
    private OnlineExamService onlineExamService;
    @Resource
    private ExamineeService examineeService;


//    @Resource
//    private RedissonClient redissonClient;


    @Value("${getRestTime}")
    private int getRestTime;


    /**
     * 通过考试id和操作人查询试题存储到reids
     * 手动加载到redis中
     *
     * @param examId   考试id
     * @param operator 操作人 可有可无
     * @author 王雪芬
     * @since 2.0.0 2018年11月21日16:01:32
     */

    @ApiOperation("通过考试id查询试题存储到reids")
    @GetMapping(value = {"/queryExamOnlineQuestionInfo/{examId}"})
    public ItooResult queryExamOnlineQuestionInfo(@ApiParam(value = "考试id") @PathVariable String examId, @RequestParam(value = "operator", required = false, defaultValue = "") String operator) {

        if (StringUtils.isEmpty(examId)) {
            return ItooResult.build(ItooResult.FAIL, "examId考试id为空");
        }

        boolean flag = onlineExamService.queryExamOnlineQuestionInfo(examId, operator);
        if (flag) {
            return ItooResult.build(ItooResult.SUCCESS, "reids存储成功");
        }
        return ItooResult.build(ItooResult.FAIL, "reids存储失败.考试id为" + examId);
    }

    /**
     * 通过考试id和操作人查询考试信息
     *
     * @param examId   考试id
     * @param operator 操作人 可有可无
     * @author 王雪芬
     * @since 2.0.0 2018年11月21日16:01:32
     */
    @ApiOperation("通过考试id查询所有考试信息")
    @GetMapping(value = {"/examOnlineInfo/{examId}"})
    public ItooResult examOnlineInfo(@ApiParam(value = "考试id", required = true) @PathVariable String examId, @RequestParam(required = false, defaultValue = "") String operator) {
        if (StringUtils.isEmpty(examId)) {
            return ItooResult.build(ItooResult.FAIL, "examid考试id为空");
        }
        List<ExamOnlineinforedisModel> examOnlineInfoList = onlineExamService.examOnlineInfo(examId, operator);
        if (CollectionUtils.isEmpty(examOnlineInfoList)) {
            return ItooResult.build(ItooResult.FAIL, "考试id:" + examId + "下没有考试信息" + examOnlineInfoList);
        }
        return ItooResult.build(ItooResult.SUCCESS, "查询所有考试信息成功", examOnlineInfoList);
    }


    /**
     * 2.根据考试id查询考生须知
     *
     * @param examId 考试id
     * @return 考生须知
     * @author 王雪芬
     * @since 2018-11-23 15:51:29
     */
    @ApiOperation("根据考生id查询考生须知")
    @GetMapping(value = {"/queryExamNotes/{examId}"})
    public ItooResult queryExamNotes(@ApiParam(value = "考试id", required = true) @PathVariable String examId) {
        if (StringUtils.isEmpty(examId)) {
            return ItooResult.build(ItooResult.FAIL, "没有考试须知,考试id为空");
        }
        ExamNotesModel examNotesModel = onlineExamService.queryExamNotes(examId);
        if (examNotesModel != null && StringUtils.isEmpty(examNotesModel.getIsStudentNotes())) {
            examNotesModel.setIsStudentNotes(1);
        }
        return ItooResult.build(ItooResult.SUCCESS, "成功", examNotesModel);
    }

    /**
     * 通过考试id或者操作人从redis中查询试题
     *
     * @param examId   考试id
     * @param operator 操作人 可有可无
     * @author 王雪芬
     * @since 2.0.0 2018年11月21日16:01:32
     */
    @ApiOperation("通过考试id或者操作人从redis中查询试题")
    @GetMapping(value = {"/examOnlineQuestionGetRedis/{examId}"})
    public ItooResult examOnlineQuestionGetRedis(@ApiParam(value = "考试id", required = true) @PathVariable String examId, @RequestParam(required = false, defaultValue = "") String operator) {
        if (StringUtils.isEmpty(examId)) {
            return ItooResult.build(ItooResult.FAIL, "examId考试id为空");
        }
        List<QuestionMainModel> examOnlineInfoList = onlineExamService.examOnlineQuestionGetRedis(examId, operator);
        if (CollectionUtils.isEmpty(examOnlineInfoList)) {
            return ItooResult.build(ItooResult.FAIL, "redis中查询试题为空");
        }
        return ItooResult.build(ItooResult.SUCCESS, "redis查询试题成功", examOnlineInfoList);
    }


    /**
     * 根据操作人id查询正在进行的考场
     *
     * @param operator 操作人
     * @author 王雪芬--于云秀修改
     * @since 2.0.0 2018年11月22日16:01:32--2018年12月29日
     */
    @ApiOperation("根据操作人id查询正在进行的考场")
    @GetMapping(value = {"/examOnlineExamRoom/{operator}"})
    public ItooResult examOnlineExamRoom(@ApiParam(value = "操作人号", required = true) @PathVariable String operator) {
        if (StringUtils.isEmpty(operator)) {
            return ItooResult.build(ItooResult.FAIL, "operator操作人不能为空");
        }

        //1.根据登录人id查询考场信息获得考试id
        //2.根据考试id查询考场信息
        //3.根据考场ID和考试id查询考生人数
        // (补偿)由于一个考场会出现两门课程,并且监考老师不是本次考试的监考老师的情况
        List<ExamRoomModel> examRoomModelList = onlineExamService.examOnlineExamRoom(operator);
        // List<ExamRoomModel> examRoomModelLists = new ArrayList<>();

//        if (examRoomModelList.size() > 0) {
//            for (ExamRoomModel em : examRoomModelList) {
//                // 根据考试id查询所有考场
//                examRoomModelLists.addAll(examRoomService.selectExamRoomList(em.getExamId(),operator));
//            }
//        }
//        examRoomModelLists = examRoomModelLists.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
//                // 利用 TreeSet 的排序去重构造函数来达到去重元素的目的
//                // 根据firstName去重
//                () -> new TreeSet<>(Comparator.comparing(ExamRoomModel::getId))), ArrayList::new));

        // 查询考场总人数
        if (examRoomModelList.size() > 0) {
            for (ExamRoomModel em : examRoomModelList) {
                List<ExamineeEntity> examinee = examineeService.selExamRoomStudentCount(em.getId(), em.getExamId());
                em.setExamRoomStudentCount(examinee.size());
                em.setNoLoginExamineeCount((examinee.stream().map(ExamineeEntity::getStudentExamState).filter(x -> x == 0).collect(Collectors.toList())).size());
            }
        }
        // 过滤考生人数为0的数据
        List<ExamRoomModel> filterList = examRoomModelList.stream().filter(ExamRoomModel -> !Objects.equals(ExamRoomModel.getExamRoomStudentCount(), 0)).collect(Collectors.toList());
        return ItooResult.build(ItooResult.SUCCESS, "查询考场成功", filterList);
    }


    /**
     * 根据操作人id查询今天和明天即将开始的考试
     *
     * @param operator 操作人
     * @author 王雪芬
     * @since 2.0.0 2018年11月22日16:01:32
     */
    @ApiOperation("根据操作人id查询今天和明天即将开始的考试")
    @GetMapping(value = {"/queryExamTimeInfo/{operator}"})
    public ItooResult queryExamTimeInfo(@ApiParam(value = "操作人号", required = true) @PathVariable String operator) {
        if (StringUtils.isEmpty(operator)) {
            return ItooResult.build(ItooResult.FAIL, "operator操作人不能为空");
        }
        List<ExaminationModel> examinationModelList = onlineExamService.queryExamTimeInfo(operator);
        return ItooResult.build(ItooResult.SUCCESS, "查询考场成功", examinationModelList);
    }


    /**
     * 考试信息确认,据学号查询当前考试(或者距离最近的考试)中学生基本信息
     *
     * @param studentId 学号
     * @author 王雪芬
     * @since 2.0.0 2018年11月22日16:01:32
     */
    @ApiOperation("考试信息确认,据学号查询当前考试(或者距离最近的考试)中学生基本信息")
    @GetMapping(value = {"/queryExamStudentInfo"})
    public ItooResult queryExamStudentInfo(@RequestParam(required = false, defaultValue = "") String studentId, @RequestParam(required = false, defaultValue = "") String exameeId) {

        if (StringUtils.isEmpty(studentId) && StringUtils.isEmpty(exameeId)) {
            return ItooResult.build(ItooResult.FAIL, "失败,学号或考生不能为空");
        }
        ExamInfoModel examInfoModel = onlineExamService.queryExamStudentInfo(studentId, exameeId);
        if (!ObjectUtils.isEmpty(examInfoModel)) {
            return ItooResult.build(ItooResult.SUCCESS, "成功", examInfoModel);
        }
        return ItooResult.build(ItooResult.FAIL, "该学生没有考试");
    }

    /**
     * 试信息确认,据学号查询当前考试(或者距离最近的考试)中学生基本信息
     *
     * @param studentId 学号
     * @author 王雪芬
     * @since 2.0.0 2018年11月22日16:01:32
     */
    @ApiOperation("考试信息确认,据学号查询当前考试(或者距离最近的考试)中学生基本信息")
    @GetMapping(value = {"/queryExamStudentInfoLogin"})
    public ItooResult queryExamStudentInfoLogin(@RequestParam(required = false, defaultValue = "") String studentId) {

        if (StringUtils.isEmpty(studentId)) {
            return ItooResult.build(ItooResult.FAIL, "失败,学号不能为空");
        }
        ExaminOnlineModel examinOnlineModel = onlineExamService.queryExamStudentInfoLogin(studentId);
        if (examinOnlineModel != null && examinOnlineModel.getStudentExamState() == 3) {
            return ItooResult.build("0003", "考生已交卷,请期待下次考试", examinOnlineModel);
        }

        if (examinOnlineModel != null && examinOnlineModel.getStudentLoginCount() != null && examinOnlineModel.getStudentLoginCount() > 1) {
            return ItooResult.build("0004", "该考生这段时间有多场考试", examinOnlineModel);
        }

        if (!ObjectUtils.isEmpty(examinOnlineModel)) {
            return ItooResult.build(ItooResult.SUCCESS, "成功", examinOnlineModel);
        }
        return ItooResult.build(ItooResult.FAIL, "该考生没有考试信息,请向管理员确认考试时间");
    }

    /**
     * 一级考试获取剩余考试时长
     *
     * @param studentCode 学号
     * @author 王雪芬
     * @since 2.0.0 2018年11月22日16:01:32
     */
    @ApiOperation("一级考试获取剩余考试时长")
    @GetMapping(value = {"/queryExamTimeOneLevel/{studentCode}"})
    public long queryExamTimeOneLevel(@ApiParam(value = "学号", required = true) @PathVariable String studentCode) {
        if (StringUtils.isEmpty(studentCode)) {
            log.info("一级考试获取考试结束时间,queryExamTimeOneLevel studentCode is null");
            return 0;
        }
        long timeLong = onlineExamService.queryExamTimeOneLevel(studentCode);
        return timeLong;
    }

    /**
     * 获取考试剩余提醒时间
     *
     * @author 王雪芬
     * @since 2.0.0 2018年11月22日16:57:37
     */
    @ApiOperation("获取考试剩余提醒时间")
    @GetMapping(value = {"/getRestTime"})
    public ItooResult getRestTime() {
        return ItooResult.build(ItooResult.SUCCESS, "获取剩余时间成功", getRestTime);
    }

    /**
     * 根据学生id交卷改变状态
     *
     * @param exameeId    考生id
     * @param examationId 考试id
     * @return 试卷实体
     * @author 王雪芬
     * @since 2.0.0 2018年11月22日21:22:58
     */

    @ApiOperation("根据学生id交卷改变状态")
    @PostMapping(value = "/updateExamStateBySumit")
    public ItooResult updateExamStateBySumit(@RequestParam String examationId, @RequestParam String exameeId) {
        ExamineeEntity examineeEntity = new ExamineeEntity();
        if (StringUtils.isEmpty(examationId) && StringUtils.isEmpty(exameeId)) {
            return ItooResult.build(ItooResult.FAIL, "失败考试或考生不能为空！");
        }

        //根据id获取考生信息
        ExamInfoModel examInfoModel = onlineExamService.queryExamStudentInfo(examationId, exameeId);
        //判断考生信息是否存在
        if (examInfoModel != null && examInfoModel.getExamineeEntity() != null) {
            BeanUtils.copyProperties(examInfoModel.getExamineeEntity(), examineeEntity);
//            examineeEntity.setStudentId(examInfoModel.getExamineeEntity().getStudentId());
//            examineeEntity.setId(examInfoModel.getExamineeEntity().getId());
        } else {
            return ItooResult.build(ItooResult.FAIL, "交卷过程中获取考生信息失败！");
        }
        boolean result = onlineExamService.updateExamStateBySumit(examineeEntity);
        if (result) {
            return ItooResult.build(ItooResult.SUCCESS, "交卷成功");
        }
        return ItooResult.build(ItooResult.FAIL, "更改交卷状态失败！");
    }

    /**
     * 根据学生id交卷改变状态(小练)
     *
     * @param exameeId    考生id
     * @param examationId 考试id
     * @return 试卷实体
     * @author 闫伟强
     * @since 2.0.0 2019年7月12日17:30:44
     */

    @ApiOperation("根据学生id交卷改变状态(小练使用)")
    @PostMapping(value = "/xiaoLianUpdateExamStateBySumit")
    public ItooResult xiaoLianUpdateExamStateBySumit(@RequestParam String examationId, @RequestParam String exameeId) {
        ExamineeEntity examineeEntity = new ExamineeEntity();
        if (StringUtils.isEmpty(examationId) && StringUtils.isEmpty(exameeId)) {
            return ItooResult.build(ItooResult.FAIL, "失败考试或考生不能为空！");
        }

        //根据id获取考生信息
        ExamInfoModel examInfoModel = onlineExamService.queryExamStudentInfo(examationId, exameeId);
        //判断考生信息是否存在
        if (examInfoModel != null && examInfoModel.getExamineeEntity() != null) {
            BeanUtils.copyProperties(examInfoModel.getExamineeEntity(), examineeEntity);
//            examineeEntity.setStudentId(examInfoModel.getExamineeEntity().getStudentId());
//            examineeEntity.setId(examInfoModel.getExamineeEntity().getId());
        } else {
            return ItooResult.build(ItooResult.FAIL, "交卷过程中获取考生信息失败！");
        }
        boolean result = onlineExamService.xiaoLianUpdateExamStateBySumit(examineeEntity);
        if (result) {
            return ItooResult.build(ItooResult.SUCCESS, "交卷成功");
        }
        return ItooResult.build(ItooResult.FAIL, "更改交卷状态失败！");
    }

    /**
     * 获取考试剩余分钟数
     *
     * @param examineeId 考生id
     * @return 剩余分钟数
     * @author 王雪芬
     * @since 2.0.0 2018年11月22日21:22:58
     */
    @ApiOperation("获取考试剩余分钟数")
    @GetMapping(value = {"/getExamRemainTime/{examineeId}"})
    public ItooResult getExamRemainTime(@ApiParam(value = "examineeId", required = true) @PathVariable String examineeId) {
        long remainTime;
        remainTime = onlineExamService.getExamRemainTime(examineeId);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", remainTime);
    }

    /**
     * 一级考试接口
     *
     * @return 剩余分钟数
     * @author 王雪芬
     * @since 2019年2月16日
     */
    @ApiOperation("一级考试存储操作题分数")
    @PostMapping(value = "/getExamOneLevel")
    public ItooResult getExamOneLevel(
            @ApiParam(name = "examOneLevelModel", value = "学号,操作题分数", required = true) @RequestBody ExamOneLevelModel examOneLevelModel) {

        if (examOneLevelModel == null || examOneLevelModel.getScore() == null || examOneLevelModel.getStudentCode() == null) {
            log.warn("一级考试存储操作题分数 examOneLevelModel is null");
            return ItooResult.build(ItooResult.FAIL, "更新分数失败");
        }
        boolean flag = onlineExamService.getExamOneLevel(examOneLevelModel.getStudentCode(), examOneLevelModel.getScore());
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", flag);
    }

    /**
     * 在线考试：根据学生ID生成本次考试试卷
     *
     * @param examationId 考试 ID
     * @return 试卷详情
     * @author 王雪芬，李娜
     * @since 2.0.0 2018-11-16 17:10:28
     */
    @ApiOperation(value = "根据学生ID生成本次考试试卷", notes = "考生 ID", tags = {"抽卷"})
    @GetMapping(value = {"/findPaperByStudentIdForOnlineExam"})
    public ItooResult findPaperByStudentIdForOnlineExam(@RequestParam(required = false, defaultValue = "") String examationId,
                                                        @RequestParam(required = false, defaultValue = "") String examineeId,
                                                        @RequestParam(required = false, defaultValue = "") String ip,
                                                        HttpServletRequest request) {
        long startTime = System.currentTimeMillis();
        //获取客户端真实IP,解决反向代理获取不了ip地址
        String clientIp=ip;
        String sessionId = request.getRequestedSessionId();
        String unKnown = "unknown";
        log.info("judy-x-forwarded-for:" + clientIp);
        if (clientIp == null || clientIp.length() == 0 || unKnown.equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("Proxy-Client-IP");
            log.info("judy-Proxy-Client-IP:" + clientIp);
        }
        if (clientIp == null || clientIp.length() == 0 || unKnown.equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("WL_Proxy-Client-IP");
            log.info("judy_WL_Proxy-Client-IP:" + clientIp);
        }
        if (clientIp == null || clientIp.length() == 0 || unKnown.equalsIgnoreCase(clientIp)) {
            //获取客户端的ip地址,如果使用了反向代理那么就不管用了
            clientIp = request.getHeader("HTTP_CLIENT_IP");
            log.info("judy_HTTP_CLIENT_IP:" + clientIp);
        }
        if (clientIp == null || clientIp.length() == 0 || unKnown.equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("HTTP_X_FORWARDED_FOR");
            log.info("judy_HTTP_X_FORWARDED_FOR:" + clientIp);
        }
        if (clientIp == null || clientIp.length() == 0 || unKnown.equalsIgnoreCase(clientIp)) {
            clientIp = request.getRemoteAddr();
            log.info("judy_request.getRemoteAddr():" + clientIp);
        }
        if (StringUtils.isEmpty(examationId) && StringUtils.isEmpty(examineeId)) {
            return ItooResult.build(ItooResult.FAIL, "失败考试id或考生id不能为空！");
        }
        // 分布式锁 - eric
        //RLock lock = redissonClient.getLock("redisson:lock:stock:" + examineeId);
        //lock.lock(3, TimeUnit.MINUTES);
        try {
            ItooResult paperByStudentIdForOnlineExam = onlineExamService.findPaperByStudentIdForOnlineExam(examationId, clientIp, examineeId, sessionId);
            System.out.println("学生抽题所用的时间"+(System.currentTimeMillis()-startTime));
            return ItooResult.build(ItooResult.SUCCESS, "查询成功", paperByStudentIdForOnlineExam);
        } finally {
            //lock.unlock();
        }
    }


    /**
     * 查询系统中所有题型信息
     *
     * @return 所有题型信息
     * @author 王雪芬
     * @since 2.0.0 2018-11-16 17:10:28
     */

    @ApiOperation(value = "查询所有题型信息")
    @GetMapping(value = {"/selectQuestionTypeId"})
    public ItooResult selectQuestionTypeId() {
        List<QuestionTypeModel> list;
        list = onlineExamService.selectQuestionTypeId();
        if (ObjectUtils.isEmpty(list)) {
            return ItooResult.build(ItooResult.FAIL, "获取题型信息失败list");
        } else {
            return ItooResult.build(ItooResult.SUCCESS, "获取题型信息成功！", list);
        }
    }

    /**
     * 二次回显答题记录
     *
     * @param examPaperModel 试卷
     * @param studentId      学生id
     * @param templateId     模板id
     * @return 返回二次回显答题记录
     * @author 王雪芬
     * @since 2.0.0 2018-11-27 17:10:28
     */

    @ApiOperation(value = "二次回显答题记录")
    @GetMapping(value = {"/getExamPaperRecord"})
    public ItooResult getExamPaperRecord(ExamPaperModel examPaperModel, String studentId, String templateId) {
        if (ObjectUtils.isEmpty(examPaperModel)) {
            return ItooResult.build(ItooResult.FAIL, "examPaperModel不能为空,studentId-{},template-{}" + studentId + templateId);
        }
        ExamPaperModel examPaperModel1 = onlineExamService.getExamPaperRecord(examPaperModel, studentId, templateId);
        if (ObjectUtils.isEmpty(examPaperModel)) {
            return ItooResult.build(ItooResult.FAIL, "二次回显答题记录失败{getExamPaperRecord}信息为空");
        }
        return ItooResult.build(ItooResult.SUCCESS, "二次回显答题记录成功", examPaperModel1);
    }

    /**
     * 在线考试：随机抽卷
     *
     * @param templateId 模板id
     * @param examineeId 考生id
     * @param courseId   课程id
     * @param operator   操作老师(该科考试的老师)
     * @author 任蒙蒙 杨晓慧
     * @since 2.0.0 2018年11月22日16:57:37
     */
    @ApiOperation("随机抽卷")
    @GetMapping(value = {"/getPaperByTemplateRandom/{templateId}/{examineeId}/{courseId}/{operator}"})
    public ExamPaperModel getPaperByTemplateRandom(@ApiParam(value = "模板 ID", required = true) @PathVariable String templateId,
                                                   @ApiParam(value = "考生 ID", required = true) @PathVariable String examineeId,
                                                   @ApiParam(value = "课程 ID", required = true) @PathVariable String courseId,
                                                   @ApiParam(value = "操作老师", required = true) @PathVariable String operator) {
        return onlineExamService.getPaperByTemplateRandom(templateId, examineeId, courseId, operator);
    }

    /**
     * 插入学生抽卷记录和答题记录
     *
     * @param examineeId     考生id
     * @param examinationId  考试id
     * @param examPaperModel 试卷详情model
     * @return 是否插入成功
     * @author 王雪芬
     * @since 2.0.0 2018-11-24 17:10:28
     */
    @ApiOperation(value = "插入学生抽卷记录和答题记录")
    @PostMapping(value = {"/insertAllPaperRecord/{examineeId}/{examinationId}"})
    public ItooResult insertAllPaperRecord
    (@ApiParam(value = "考生id", required = true) @PathVariable String examineeId,
     @ApiParam(value = "考试id", required = true) @PathVariable String examinationId,
     @RequestBody ExamPaperModel examPaperModel) {
        if (ObjectUtils.isEmpty(examPaperModel)) {
            return ItooResult.build(ItooResult.FAIL, "试卷详情model为空！");
        }
        List<PaperRecordEntity> paperRecordEntityList = onlineExamService.insertAllPaperRecord(examineeId, examinationId, examPaperModel);
        if (!CollectionUtils.isEmpty(paperRecordEntityList)) {
            return ItooResult.build(ItooResult.SUCCESS, "插入学生抽卷记录和答题记录成功！");
        } else {
            return ItooResult.build(ItooResult.FAIL, "插入学生抽卷记录和答题记录失败!");
        }
    }

    /**
     * 根据答题记录中的试卷或模版id和考生id查询试卷
     *
     * @param examineeId 考生id
     * @param templateId 试卷或模版id
     * @return 所有题型信息 ExamPaperModel
     * @author 王雪芬
     * @since 2.0.0 2018-11-24 17:10:28
     */
    @ApiOperation(value = "根据答题记录中的试卷或模版id和学生id查询试卷")
    @GetMapping(value = {"/queryPaperAndRecord/{examineeId}/{templateId}"})
    public ItooResult queryPaperAndRecord(@ApiParam(value = "学生id", required = true) @PathVariable String examineeId, @ApiParam(value = "试卷或模版id", required = true) @PathVariable String templateId) {

        ExamPaperModel examPaper = onlineExamService.queryPaperAndRecord(examineeId, templateId);
        if (examPaper != null) {
            return ItooResult.build(ItooResult.SUCCESS, "根据答题记录中的考试id和学生id查询试卷成功！", examPaper);
        } else {
            return ItooResult.build(ItooResult.FAIL, "根据答题记录中的考试id和学生id查询试卷失败！");
        }

    }

    /**
     * 根据模版id和考生id查询试卷-二次判分显示试卷
     *
     * @param examineeId 考生id
     * @param templateId 试卷或模版id
     * @return 所有题型信息 ExamPaperModel
     * @author 樊建华
     * @since 2.0.0 2018年12月26日20:33:47
     */
    @ApiOperation(value = "根据模版id和学生id查询试卷")
    @GetMapping(value = {"/queryExamination/{examineeId}/{templateId}"})
    public ItooResult queryExamination(@ApiParam(value = "学生id", required = true) @PathVariable String examineeId, @ApiParam(value = "试卷或模版id", required = true) @PathVariable String templateId) {

        ItooResult examPaper = onlineExamService.queryExamination(examineeId, templateId);
        if (examPaper != null) {
            return ItooResult.build(ItooResult.SUCCESS, "根据答题记录中的考试id和学生id查询试卷成功！", examPaper);
        } else {
            return ItooResult.build(ItooResult.FAIL, "根据答题记录中的考试id和学生id查询试卷失败！");
        }
    }

    /**
     * 判断二次登陆密码是否正确
     *
     * @param password 二次登陆密码
     * @return 布尔值
     * @author 王雪芬
     * @since 2.0.0 2018年11月26日12:14:37
     */
    @ApiOperation(value = "验证二次登录密码")
    @GetMapping(value = {"/getSecordLoginPassword/{password}"})
    public ItooResult getSecordLoginPassword(@ApiParam(value = "密码", required = true) @PathVariable String password) {
        boolean flag;
        flag = onlineExamService.getSecordLoginPassword(password);
        if (flag) {
            return ItooResult.build(ItooResult.SUCCESS, "查询考试确认信息成功！", true);
        }
        return ItooResult.build(ItooResult.FAIL, "获取二次登陆密码信息出错！", false);
    }

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String UPDATE_EXAM_PAPER="update:exam:paper:";

    /**
     * 更新答题记录
     *
     * @param paperOnlineRecordModel 试卷内容
     * @return flag 是否更新答题记录成功
     * @author 王雪芬
     * @since 2.0.0 2018年12月2日15:54:37
     */
    @ApiOperation(value = "更新答题记录")
    @PostMapping(value = {"/updateExamPaperRecord"})
    public ItooResult updateExamPaperRecord(@RequestBody PaperOnlineRecordModel paperOnlineRecordModel) {
        if (ObjectUtils.isEmpty(paperOnlineRecordModel)) {
            return ItooResult.build(ItooResult.FAIL, "paperRecordModel不能为空");
        }

        redisTemplate.opsForValue().getAndSet(UPDATE_EXAM_PAPER+paperOnlineRecordModel.getPaperRecordId(),"");


        boolean flag;
        flag = onlineExamService.updateExamPaperRecord(paperOnlineRecordModel);
        if (flag) {
            return ItooResult.build(ItooResult.SUCCESS, "更新答题记录成功", true);
        }
        return ItooResult.build(ItooResult.FAIL, "更新答题记录失败", false);
    }


    /**
     * 查询调查问卷
     *
     * @return flag 问卷详情
     * @author 王雪芬
     * @since 2.0.0 2018年12月17日15:54:37
     */
    @ApiOperation(value = "查询调查问卷")
    @GetMapping(value = {"findQuestionNaire"})
    public ItooResult findQuestionNaire() {
        ItooResult questionNaireALLInfoModel = onlineExamService.findQuestionNaire();
        return ItooResult.build(ItooResult.SUCCESS, "查询问卷调查成功", questionNaireALLInfoModel);
    }


    /**
     * 给模板使用浏览试卷
     *
     * @return flag 给模板使用浏览试卷
     * @author 王雪芬
     * @since 2.0.0 2018年12月17日15:54:37
     */
    @ApiOperation(value = " 给模板使用浏览试卷")
    @GetMapping(value = {"/queryQuestionTempleate/{courseId}/{templeateId}/{operator}"})
    public ItooResult queryQuestionTempleate(@ApiParam(value = "课程id", required = true) @PathVariable String courseId, @ApiParam(value = "模板id", required = true) @PathVariable String templeateId, @ApiParam(value = "operator用户id", required = true) @PathVariable String operator) {
        if (courseId == null) {
            log.warn("课程id不能为空");
        }
        if (templeateId == null) {
            log.warn("模板id不能为空");
        }
        ItooResult paperByStudentIdForOnlineExam = onlineExamService.queryQuestionTempleate(courseId, templeateId, operator);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", paperByStudentIdForOnlineExam);

    }

    /**
     * 重新抽卷
     *
     * @param examRecoverModel 重新抽卷信息
     * @return flag 重新抽卷
     * @author 王雪芬
     * @since 2.0.0 2018年12月22日15:54:37
     */
    @ApiOperation(value = "重新抽卷")
    @PostMapping(value = {"/queryRecoverQuestionPerson"})
    public ItooResult queryRecoverQuestionPerson(@RequestBody ExamRecoverModel examRecoverModel) {
        if (examRecoverModel == null) {
            return ItooResult.build(ItooResult.FAIL, "examRecoverModel为空,重新抽卷");
        }

        ItooResult examPaperQuestion = onlineExamService.queryRecoverQuestionPerson(examRecoverModel);
        return ItooResult.build(ItooResult.SUCCESS, "重新抽卷成功", examPaperQuestion);
    }

    /**
     * 修改抽到错题的考生的错题,放到redis
     *
     * @param examineeModelList 考生list
     * @param oldQuestionId     旧题Id
     * @param newQuestionId     新题Id
     * @author 任蒙蒙
     * @since 2.0.0 2018-11-17 17:10:28
     */
    @ApiOperation(value = "修改抽到错题的考生的错题,放到redis")
    @PostMapping(value = {"/updateWrongQuesForExaminee/{oldQuestionId}/{newQuestionId}"})
    public ItooResult updateWrongQuesForExaminee(@RequestBody List<ExamineeModel> examineeModelList, @PathVariable String oldQuestionId, @PathVariable String newQuestionId) {
        boolean flag;
        flag = onlineExamService.updateWrongQuesForExaminee(examineeModelList, oldQuestionId, newQuestionId);
        if (flag) {
            return ItooResult.build(ItooResult.SUCCESS, "您好,抽到错题的考生修改试题成功,请通知考生刷新界面即可", true);
        }
        return ItooResult.build(ItooResult.FAIL, "您好,抽到错题的考生修改试题失败,请联系管理员", false);
    }

    /**
     * 固定抽题-随堂小练用
     *
     * @return flag 给固定抽题-随堂小练显示试卷
     * @author 任蒙蒙
     * @since 2.0.0 2019年1月29日19:32:01
     */
    @ApiOperation(value = " 固定抽题-随堂小练用")
    @GetMapping(value = {"/queryQuestionForFix/{courseId}/{templateId}/{operator}"})
    public ItooResult queryQuestionForFix(@ApiParam(value = "课程id", required = true) @PathVariable String courseId, @ApiParam(value = "模板id", required = true) @PathVariable String templateId, @ApiParam(value = "operator用户id", required = true) @PathVariable String operator) {
        if (courseId == null) {
            log.warn("课程id不能为空");
        }
        if (templateId == null) {
            log.warn("模板id不能为空");
        }
        ExamPaperModel paperByStudentIdForOnlineExam = onlineExamService.queryQuestionForFix(courseId, templateId, operator);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", paperByStudentIdForOnlineExam);

    }


    /**
     * 一级考下载学号到c盘
     *
     * @return flag 一级考下载学号到c盘
     * @author 王雪芬
     * @since 2.0.0 2019年2月23日08:13:28
     */
    @ApiOperation(value = " 一级考下载学号到c盘")
    @GetMapping(value = {"/downLoadStudentOneLevel/{studentCode}"})
    public ItooResult downLoadStudentOneLevel(@ApiParam(value = "学号", required = true) @PathVariable String studentCode) {
        if (studentCode == null) {
            log.warn("课程id不能为空");
            return ItooResult.build(ItooResult.FAIL, "学号不能为空");
        }
        boolean paperByStudentIdForOnlineExam = onlineExamService.downLoadStudentOneLevel(studentCode);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", paperByStudentIdForOnlineExam);
    }


    /**
     * 一级考下载操作系统文件
     *
     * @return flag 一级考下载操作系统文件
     * @author 王雪芬
     * @since 2.0.0 2019年2月23日08:13:28
     */
    @ApiOperation(value = " 一级考下载操作系统文件")
    @GetMapping(value = {"/downStudentOneLevelSystem/{studentCode}"})
    public ItooResult downStudentOneLevelSystem(HttpServletResponse response, @ApiParam(value = "学号", required = true) @PathVariable String studentCode) throws Exception {
        if (studentCode == null) {
            log.warn("学号不能为空");
            return ItooResult.build(ItooResult.FAIL, "学号不能为空");
        }
        String filename = studentCode + ".exe";
        filename = new String(filename.getBytes("iso8859-1"), "UTF-8");
        //File file = new File("D:/from.txt");
        String path = "/opt/1.exe";
//        String path = "/opt/from.txt";

        File file = new File(path);

        //如果文件不存在
        if (!file.exists()) {
            return ItooResult.build(ItooResult.FAIL, "下载失败");
        }
        //设置响应头，控制浏览器下载该文件
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
//        //读取要下载的文件，保存到文件输入流
        FileInputStream in = new FileInputStream(path);
        //创建输出流
        OutputStream out = response.getOutputStream();
        //缓存区
        byte buffer[] = new byte[1024];
        int len = 0;
        //循环将输入流中的内容读取到缓冲区中
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        //关闭
        in.close();
        out.close();
        return ItooResult.build(ItooResult.SUCCESS, "下载成功");
    }


    /**
     * 课程练习-保存学生答题记录
     *
     * @param coursePaperRecordModel
     * @return 是否插入成功
     * @author 贾建清
     * @since 2.0.0 2019-3-26 15:48:15
     */
    @ApiOperation(value = "课程练习-保存学生答题记录")
    @PostMapping(value = {"/insertPaperRecord"})
    public ItooResult insertPaperRecord(@RequestBody CoursePaperRecordModel coursePaperRecordModel) {
        if (ObjectUtils.isEmpty(coursePaperRecordModel)) {
            return ItooResult.build(ItooResult.FAIL, "试卷详情model为空！");
        }
        List<PaperRecordEntity> paperRecordEntityList = onlineExamService.insertPaperRecord(coursePaperRecordModel);
        if (!CollectionUtils.isEmpty(paperRecordEntityList)) {
            return ItooResult.build(ItooResult.SUCCESS, "保存学生答题记录成功！");
        } else {
            return ItooResult.build(ItooResult.FAIL, "保存学生答题记录失败!");
        }
    }


    /**
     * 用于模板下载word文档
     *
     * @return 用于模板下载word文档，返回word对象，用于下载
     * @author 程金鹏
     * @since 2.0.0 2019年5月17日21:01:21
     */
    @ApiOperation(value = " 用于模板下载word文档，返回word对象，用于下载")
    @GetMapping(value = {"/queryQuestionTempleateAndDownload/{courseId}/{templeateId}/{operator}"})
    public ItooResult queryQuestionTempleateAndDownload(@ApiParam(value = "课程id", required = true) @PathVariable String courseId, @ApiParam(value = "模板id", required = true) @PathVariable String templeateId, @ApiParam(value = "operator用户id", required = true) @PathVariable String operator) {
        if (courseId == null) {
            log.warn("课程id不能为空");
        }
        if (templeateId == null) {
            log.warn("模板id不能为空");
        }
        ItooResult paperByStudentIdForOnlineExam = onlineExamService.queryQuestionTempleate(courseId, templeateId, operator);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", paperByStudentIdForOnlineExam);

    }

}



